
package com.hlkj.pay.app.order.impl;
/*
 * Hlpay-Plus aggregate payment system.
 * Copyright (c) 2024-2025 Hlpay Team Copyright has the right of final interpretation.
 */

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;

import com.hlkj.framework.common.pojo.CommonResult;
import com.hlkj.framework.common.pojo.LocalContext;
import com.hlkj.framework.common.util.json.JsonUtils;
import com.hlkj.pay.app.common.IAuthCodeService;
import com.hlkj.pay.app.merchant.impl.CommonChannelCallHandler;
import com.hlkj.pay.app.order.ITransferOrderAppService;
import com.hlkj.pay.app.order.IWithdrawOrderAppService;
import com.hlkj.pay.common.CommonResultCode;
import com.hlkj.pay.common.MerchantResultCode;
import com.hlkj.pay.common.OpenApiResultCode;
import com.hlkj.pay.common.PayResultCode;
import com.hlkj.pay.dto.LocalMerchantRequest;
import com.hlkj.pay.dto.merchant.VirtualBalanceDto;
import com.hlkj.pay.dto.order.NotifyOrderTransferDto;
import com.hlkj.pay.dto.order.OrderTransferVerifyDto;
import com.hlkj.pay.enums.CommonEnum;
import com.hlkj.pay.enums.MerchantEnum;
import com.hlkj.pay.enums.PayOrderEnums;
import com.hlkj.pay.gateway.merchant.IMerchantReportGateway;
import com.hlkj.pay.gateway.order.IChannelTransferGateway;
import com.hlkj.pay.infrastructure.model.merchant.MerchantAppChannelDO;
import com.hlkj.pay.infrastructure.model.order.OrderTransferDO;
import com.hlkj.pay.infrastructure.model.pay.ProviderChannelConfigDO;
import com.hlkj.pay.service.merchant.IMerchantApplicationService;
import com.hlkj.pay.service.order.ITransferOrderService;
import com.hlkj.pay.service.pay.IProviderService;
import com.hlkj.pay.util.MerchantUtils;
import com.hlkj.pay.util.OrderCodeUtil;
import com.hlkj.pay.vo.openapi.order.req.OpenApiOrderQueryReq;
import com.hlkj.pay.vo.openapi.order.req.OpenApiOrderTransferPreReq;
import com.hlkj.pay.vo.openapi.order.req.OpenApiOrderTransferReq;
import com.hlkj.pay.vo.openapi.order.req.OpenApiOrderWithdrawReq;
import com.hlkj.pay.vo.openapi.order.resp.OpenApTransferBalanceResp;
import com.hlkj.pay.vo.openapi.order.resp.OpenApiOrderTransferResp;
import com.hlkj.pay.vo.openapi.order.resp.OpenApiOrderWithdrawResp;
import com.hlkj.pay.vo.order.req.OrderTransferPreReq;
import com.hlkj.pay.vo.order.req.OrderTransferReq;
import com.hlkj.pay.vo.order.req.OrderWithdrawReq;
import com.hlkj.pay.vo.order.resp.OrderTransferResp;
import com.hlkj.pay.vo.order.resp.OrderWithdrawResp;

import cn.hutool.core.bean.BeanUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author HlpayTeam
 * @date 2024/10/09 13:50
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Validated
public class TransferOrderAppServiceImpl implements ITransferOrderAppService {

    private final IProviderService providerService;

    private final IChannelTransferGateway channelTransferGateway;

    private final IMerchantReportGateway merchantReportGateway;

    private final CommonChannelCallHandler commonChannelCallHandler;

    private final ITransferOrderService transferOrderService;

    private final OrderNotifyHandler orderNotifyHandler;

    private final OrderCodeUtil orderCodeUtil;

    private final IMerchantApplicationService merchantApplicationService;

    private final IWithdrawOrderAppService withdrawOrderAppService;

    private final IAuthCodeService authCodeService;

    @Override
    public String orderStatusCallBack(String channelCode, String providerCode, HttpServletRequest request) {
        // 获取通道配置
        ProviderChannelConfigDO providerChannelConfigDO = providerService.queryConfig(providerCode, channelCode);
        if (providerChannelConfigDO == null) {
            return processOrderCallBackErrorResponse(channelCode, providerCode, null, null, CommonResult.error(PayResultCode.PROVIDER_CHANNEL_NOT_EXITS));
        }
        CommonResult<NotifyOrderTransferDto> commonResult = channelTransferGateway.orderStatusParse(request, providerChannelConfigDO);
        if (!commonResult.isSuccess()) {
            if (MerchantResultCode.MERCHANT_CHANNEL_CALLBACK_SIGN_ERROR.getCode().equals(commonResult.getCode())) {
                NotifyOrderTransferDto notifyOrderTransferDto = commonResult.getData();
                if (notifyOrderTransferDto != null && StringUtils.hasText(notifyOrderTransferDto.getPayOrderNo())
                        && MerchantEnum.PROCESS_STATUS.SUCCESS.getCode().equals(notifyOrderTransferDto.getStatus().getCode())) {
                    OrderTransferDO orderTransferDO = transferOrderService.queryPayOrder(notifyOrderTransferDto.getPayOrderNo());
                    if (orderTransferDO == null) {
                        log.info("收到转账订单回调,签名错误,通过回调订单查询订单数据不存在 payOrderNo:{}", notifyOrderTransferDto.getPayOrderNo());
                        return commonResult.getMsg();
                    }
                    log.info("收到转账订单回调,签名错误,通过回调订单回查第三方支付状态 payOrderNo:{}", notifyOrderTransferDto.getPayOrderNo());
                    queryPayStatus(orderTransferDO);
                    return processOrderCallBackSuccessResponse(channelCode, orderTransferDO, notifyOrderTransferDto.getCallbackBody(), CommonResult.success(),
                            providerChannelConfigDO);
                }
                else {
                    return commonResult.getMsg();
                }
            }
            return commonResult.getMsg();
        }
        return processCallBack(channelCode, commonResult.getData(), providerChannelConfigDO);
    }

    @Override
    public CommonResult<OpenApiOrderTransferResp> submitPreOrder(@Valid OpenApiOrderTransferPreReq orderTransferReq) {
        log.info("orderTransfer submitPreOrder orderTransferReq:{}", JsonUtils.toJsonString(orderTransferReq));
        try {
            LocalMerchantRequest localMerchantRequest = (LocalMerchantRequest) LocalContext.get();
            if (StringUtils.isEmpty(orderTransferReq.getMchOrderNo())) {
                return CommonResult.error(CommonResultCode.PARAMETER_MISSING);
            }
            MerchantAppChannelDO merchantAppChannelDO = merchantApplicationService.queryAppChannelDetail(orderTransferReq.getOutMchChannelCode());
            if (merchantAppChannelDO == null) {
                return CommonResult.error(OpenApiResultCode.MERCHANT_APP_CHANNEL_NOT_EXIST);
            }
            OrderTransferDO orderTransferDO = transferOrderService.queryByMchOrderNo(localMerchantRequest.getSn(), orderTransferReq.getMchOrderNo());
            if (orderTransferDO != null) {
                return CommonResult.error(OpenApiResultCode.DATA_HAS_EXIST);
            }
            boolean extensionExist = channelTransferGateway.extensionExist(merchantAppChannelDO.getChannelCode());
            if (!extensionExist) {
                return CommonResult.error(CommonResultCode.EXTENSION_NOT_EXIST);
            }
            OrderTransferDO orderTransfer = BeanUtil.copyProperties(orderTransferReq, OrderTransferDO.class);
            orderTransfer.setSn(localMerchantRequest.getSn());
            orderTransfer.setPayOrderNo(orderCodeUtil.orderNo(PayOrderEnums.ORDER_NO_TYPE.WITHDRAW));
            orderTransfer.setStatus(MerchantEnum.PROCESS_STATUS.INIT.getCode());
            orderTransfer.setAppId(localMerchantRequest.getAppId());
            orderTransfer.setSignType(localMerchantRequest.getSignType());
            orderTransfer.setMchChannelCode(orderTransferReq.getOutMchChannelCode());
            orderTransfer.setProviderCode(merchantAppChannelDO.getProviderCode());
            orderTransfer.setChannelCode(merchantAppChannelDO.getChannelCode());
            CommonResult<OrderTransferDO> commonResult = channelTransferGateway.submitChannelOrderApply(merchantAppChannelDO, orderTransfer);
            if (!commonResult.isSuccess()) {
                return CommonResult.error(commonResult.getCode(), commonResult.getMsg());
            }
            OrderTransferDO updateOrderTransfer = commonResult.getData();
            orderTransfer.setRemark(updateOrderTransfer.getRemark());
            orderTransfer.setMessage(updateOrderTransfer.getMessage());
            orderTransfer.setStatus(updateOrderTransfer.getStatus());
            transferOrderService.addTransferOrder(orderTransfer);
            return CommonResult.success(BeanUtil.copyProperties(orderTransfer, OpenApiOrderTransferResp.class));
        }
        catch (Exception e) {
            log.error("orderTransfer submitPreOrder error:{}", e.getMessage(), e);
            return CommonResult.error(CommonResultCode.SERVICE_ERROR);
        }
    }

    @Override
    public CommonResult<OpenApiOrderTransferResp> submitOrder(@Valid OpenApiOrderTransferReq orderTransferReq) {
        log.info("orderTransfer submitOrder orderTransferReq:{}", JsonUtils.toJsonString(orderTransferReq));
        try {
            LocalMerchantRequest localMerchantRequest = (LocalMerchantRequest) LocalContext.get();
            OrderTransferDO orderTransfer = null;
            // 部分通道为二步
            if (StringUtils.isEmpty(orderTransferReq.getPayOrderNo()) && StringUtils.isEmpty(orderTransferReq.getSmsCode())) {
                if (StringUtils.hasText(orderTransferReq.getPayOrderNo())) {
                    orderTransfer = transferOrderService.queryPayOrder(orderTransferReq.getPayOrderNo());
                }
                else {
                    orderTransfer = transferOrderService.queryByMchOrderNo(localMerchantRequest.getSn(), orderTransferReq.getMchOrderNo());
                }
                if (orderTransfer == null) {
                    return CommonResult.error(OpenApiResultCode.DATA_NOT_EXIST);
                }
                if (!orderTransfer.getSn().equals(localMerchantRequest.getSn())) {
                    return CommonResult.error(OpenApiResultCode.DATA_NOT_EXIST);
                }
            }
            else {
                MerchantAppChannelDO merchantAppChannelDO = merchantApplicationService.queryAppChannelDetail(orderTransferReq.getOutMchChannelCode());
                if (merchantAppChannelDO == null) {
                    return CommonResult.error(OpenApiResultCode.MERCHANT_APP_CHANNEL_NOT_EXIST);
                }
                orderTransfer = BeanUtil.copyProperties(orderTransferReq, OrderTransferDO.class);
                orderTransfer.setSn(localMerchantRequest.getSn());
                orderTransfer.setPayOrderNo(orderCodeUtil.orderNo(PayOrderEnums.ORDER_NO_TYPE.WITHDRAW));
                orderTransfer.setStatus(MerchantEnum.PROCESS_STATUS.INIT.getCode());
                orderTransfer.setAppId(localMerchantRequest.getAppId());
                orderTransfer.setSignType(localMerchantRequest.getSignType());
                orderTransfer.setMchChannelCode(orderTransferReq.getOutMchChannelCode());
                orderTransfer.setProviderCode(merchantAppChannelDO.getProviderCode());
                orderTransfer.setChannelCode(merchantAppChannelDO.getChannelCode());
            }
            OrderTransferVerifyDto orderTransferVerifyDto = new OrderTransferVerifyDto();
            orderTransferVerifyDto.setSmsCode(orderTransferReq.getSmsCode());
            CommonResult<OrderTransferDO> commonResult = channelTransferGateway.submitTransferOrder(orderTransferVerifyDto, orderTransfer);
            if (!commonResult.isSuccess()) {
                return CommonResult.error(commonResult.getCode(), commonResult.getMsg());
            }
            OrderTransferDO updateOrderTransfer = commonResult.getData();
            if (orderTransfer.getId() == null) {
                orderTransfer.setRemark(updateOrderTransfer.getRemark());
                orderTransfer.setMessage(updateOrderTransfer.getMessage());
                orderTransfer.setStatus(updateOrderTransfer.getStatus());
                addPayOrder(orderTransfer);
            }
            else {
                updatePayOrder(updateOrderTransfer, orderTransfer);
            }
            return CommonResult.success(BeanUtil.copyProperties(orderTransfer, OpenApiOrderTransferResp.class));
        }
        catch (Exception e) {
            log.error("orderTransfer submitOrder error:{}", e.getMessage(), e);
            return CommonResult.error(CommonResultCode.SERVICE_ERROR);
        }
    }

    @Override
    public CommonResult<OpenApiOrderTransferResp> queryOrder(OpenApiOrderQueryReq orderQueryReq) {
        log.info("orderTransfer queryOrder orderQueryReq:{}", JsonUtils.toJsonString(orderQueryReq));
        try {
            LocalMerchantRequest localMerchantRequest = (LocalMerchantRequest) LocalContext.get();
            if (StringUtils.isEmpty(orderQueryReq.getPayOrderNo()) && StringUtils.isEmpty(orderQueryReq.getMchOrderNo())) {
                return CommonResult.error(CommonResultCode.PARAMETER_MISSING);
            }
            OrderTransferDO orderTransferDO;
            if (StringUtils.hasText(orderQueryReq.getPayOrderNo())) {
                orderTransferDO = transferOrderService.queryPayOrder(orderQueryReq.getPayOrderNo());
            }
            else {
                orderTransferDO = transferOrderService.queryByMchOrderNo(localMerchantRequest.getSn(), orderQueryReq.getMchOrderNo());
            }
            if (orderTransferDO == null) {
                return CommonResult.error(OpenApiResultCode.DATA_NOT_EXIST);
            }
            if (!orderTransferDO.getSn().equals(localMerchantRequest.getSn())) {
                return CommonResult.error(OpenApiResultCode.DATA_NOT_EXIST);
            }
            MerchantEnum.PROCESS_STATUS processStatus = MerchantEnum.PROCESS_STATUS.from(orderTransferDO.getStatus());
            switch (processStatus) {
                case SUCCESS:
                case FAIL:
                    break;
                default:
                    // 需要同步状态
                    queryPayStatus(orderTransferDO);
            }
            return CommonResult.success(BeanUtil.copyProperties(orderTransferDO, OpenApiOrderTransferResp.class));
        }
        catch (Exception e) {
            log.error("orderTransfer queryOrder error:{}", e.getMessage(), e);
            return CommonResult.error(CommonResultCode.SERVICE_ERROR);
        }
    }

    @Override
    public CommonResult<OpenApTransferBalanceResp> balanceQuery(String mchChannelCode) {
        MerchantAppChannelDO merchantAppChannelDO = merchantApplicationService.queryAppChannelDetail(mchChannelCode);
        if (merchantAppChannelDO == null) {
            return CommonResult.error(OpenApiResultCode.MERCHANT_APP_CHANNEL_NOT_EXIST);
        }
        boolean extensionExist = channelTransferGateway.extensionExist(merchantAppChannelDO.getChannelCode());
        if (!extensionExist) {
            return CommonResult.error(CommonResultCode.EXTENSION_NOT_EXIST);
        }
        CommonResult<VirtualBalanceDto> commonResult = merchantReportGateway.balanceQuery(mchChannelCode);
        if (!commonResult.isSuccess()) {
            return CommonResult.error(OpenApiResultCode.PROCESS_ERROR.getCode(), commonResult.getMsg());
        }
        VirtualBalanceDto commonResultData = commonResult.getData();
        OpenApTransferBalanceResp openApTransferBalanceResp = new OpenApTransferBalanceResp();
        openApTransferBalanceResp.setBalance(MerchantUtils.bigDecimalToString2(commonResultData.getBalance()));
        openApTransferBalanceResp.setFrozenBalance(MerchantUtils.bigDecimalToString2(commonResultData.getFrozenBalance()));
        return CommonResult.success(openApTransferBalanceResp);
    }

    @Override
    public CommonResult<OrderTransferResp> submitPreOrder(OrderTransferPreReq orderTransferReq) {
        log.info("admin orderTransfer submitPreOrder orderTransferReq:{}", JsonUtils.toJsonString(orderTransferReq));
        try {
            MerchantAppChannelDO outMerchantAppChannelDO = merchantApplicationService.queryAppChannelDetail(orderTransferReq.getOutMchChannelCode());
            if (outMerchantAppChannelDO == null) {
                return CommonResult.error(OpenApiResultCode.MERCHANT_APP_CHANNEL_NOT_EXIST);
            }
            MerchantAppChannelDO inMerchantAppChannelDO = merchantApplicationService.queryAppChannelDetail(orderTransferReq.getInMchChannelCode());
            if (inMerchantAppChannelDO == null) {
                return CommonResult.error(OpenApiResultCode.MERCHANT_APP_CHANNEL_NOT_EXIST);
            }
            boolean extensionExist = channelTransferGateway.extensionExist(outMerchantAppChannelDO.getChannelCode());
            if (!extensionExist) {
                return CommonResult.error(CommonResultCode.EXTENSION_NOT_EXIST);
            }
            OrderTransferDO orderTransfer = BeanUtil.copyProperties(orderTransferReq, OrderTransferDO.class);
            orderTransfer.setSn(outMerchantAppChannelDO.getSn());
            orderTransfer.setPayOrderNo(orderCodeUtil.orderNo(PayOrderEnums.ORDER_NO_TYPE.WITHDRAW));
            orderTransfer.setStatus(MerchantEnum.PROCESS_STATUS.INIT.getCode());
            orderTransfer.setAppId(outMerchantAppChannelDO.getAppId());
            orderTransfer.setMchChannelCode(orderTransferReq.getOutMchChannelCode());
            orderTransfer.setProviderCode(outMerchantAppChannelDO.getProviderCode());
            orderTransfer.setChannelCode(outMerchantAppChannelDO.getChannelCode());
            orderTransfer.setClientIp(LocalContext.get().getIp());
            CommonResult<OrderTransferDO> commonResult = channelTransferGateway.submitChannelOrderApply(outMerchantAppChannelDO, orderTransfer);
            if (!commonResult.isSuccess()) {
                return CommonResult.error(commonResult.getCode(), commonResult.getMsg());
            }
            OrderTransferDO updateOrderTransfer = commonResult.getData();
            // 执行失败
            if(MerchantEnum.PROCESS_STATUS.FAIL.getCode() == updateOrderTransfer.getStatus()){
                return CommonResult.error(0, updateOrderTransfer.getMessage());
            }
            orderTransfer.setRemark(updateOrderTransfer.getRemark());
            orderTransfer.setMessage(updateOrderTransfer.getMessage());
            orderTransfer.setStatus(updateOrderTransfer.getStatus());
            orderTransfer.setInUserId(updateOrderTransfer.getInUserId());
            orderTransfer.setOutUserId(updateOrderTransfer.getOutUserId());
            transferOrderService.addTransferOrder(orderTransfer);
            return CommonResult.success(BeanUtil.copyProperties(orderTransfer, OrderTransferResp.class));
        }
        catch (Exception e) {
            log.error("admin orderTransfer submitPreOrder error:{}", e.getMessage(), e);
            return CommonResult.error(CommonResultCode.SERVICE_ERROR);
        }
    }

    @Override
    public CommonResult<OrderTransferResp> submitOrder(OrderTransferReq orderTransferReq) {
        log.info("admin orderTransfer submitOrder orderTransferReq:{}", JsonUtils.toJsonString(orderTransferReq));
        try {
            OrderTransferDO orderTransfer = null;
            // 部分通道为二步
            if (StringUtils.hasText(orderTransferReq.getPayOrderNo()) && StringUtils.hasText(orderTransferReq.getSmsCode())) {
                if (StringUtils.hasText(orderTransferReq.getPayOrderNo())) {
                    orderTransfer = transferOrderService.queryPayOrder(orderTransferReq.getPayOrderNo());
                }
                if (orderTransfer == null) {
                    return CommonResult.error(OpenApiResultCode.DATA_NOT_EXIST);
                }
            }
            else {
                MerchantAppChannelDO outMerchantAppChannelDO = merchantApplicationService.queryAppChannelDetail(orderTransferReq.getOutMchChannelCode());
                if (outMerchantAppChannelDO == null) {
                    return CommonResult.error(OpenApiResultCode.MERCHANT_APP_CHANNEL_NOT_EXIST);
                }
                MerchantAppChannelDO inMerchantAppChannelDO = merchantApplicationService.queryAppChannelDetail(orderTransferReq.getInMchChannelCode());
                if (inMerchantAppChannelDO == null) {
                    return CommonResult.error(OpenApiResultCode.MERCHANT_APP_CHANNEL_NOT_EXIST);
                }
                boolean extensionExist = channelTransferGateway.extensionExist(outMerchantAppChannelDO.getChannelCode());
                if (!extensionExist) {
                    return CommonResult.error(CommonResultCode.EXTENSION_NOT_EXIST);
                }
                orderTransfer = BeanUtil.copyProperties(orderTransferReq, OrderTransferDO.class);
                orderTransfer.setSn(outMerchantAppChannelDO.getSn());
                orderTransfer.setPayOrderNo(orderCodeUtil.orderNo(PayOrderEnums.ORDER_NO_TYPE.WITHDRAW));
                orderTransfer.setStatus(MerchantEnum.PROCESS_STATUS.INIT.getCode());
                orderTransfer.setAppId(outMerchantAppChannelDO.getAppId());
                orderTransfer.setMchChannelCode(orderTransferReq.getOutMchChannelCode());
                orderTransfer.setProviderCode(outMerchantAppChannelDO.getProviderCode());
                orderTransfer.setChannelCode(outMerchantAppChannelDO.getChannelCode());
                orderTransfer.setClientIp(LocalContext.get().getIp());
            }
            OrderTransferVerifyDto orderTransferVerifyDto = new OrderTransferVerifyDto();
            orderTransferVerifyDto.setSmsCode(orderTransferReq.getSmsCode());
            CommonResult<OrderTransferDO> commonResult = channelTransferGateway.submitTransferOrder(orderTransferVerifyDto, orderTransfer);
            if (!commonResult.isSuccess()) {
                return CommonResult.error(commonResult.getCode(), commonResult.getMsg());
            }
            OrderTransferDO updateOrderTransfer = commonResult.getData();
            if (orderTransfer.getId() == null) {
                orderTransfer.setRemark(updateOrderTransfer.getRemark());
                orderTransfer.setMessage(updateOrderTransfer.getMessage());
                orderTransfer.setStatus(updateOrderTransfer.getStatus());
                orderTransfer.setInUserId(updateOrderTransfer.getInUserId());
                orderTransfer.setOutUserId(updateOrderTransfer.getOutUserId());
                addPayOrder(orderTransfer);
            }
            else {
                updatePayOrder(updateOrderTransfer, orderTransfer);
            }
            return CommonResult.success(BeanUtil.copyProperties(orderTransfer, OrderTransferResp.class));
        }
        catch (Exception e) {
            log.error("admin orderTransfer submitOrder error:{}", e.getMessage(), e);
            return CommonResult.error(CommonResultCode.SERVICE_ERROR);
        }
    }

    String processOrderCallBackSuccessResponse(String channelCode, OrderTransferDO orderTransferDO, String callBackBody, CommonResult commonResult,
            ProviderChannelConfigDO providerChannelConfigDO) {
        if (orderTransferDO != null) {
            LocalMerchantRequest localMerchantRequest = (LocalMerchantRequest) LocalContext.get();
            localMerchantRequest.setProviderCode(orderTransferDO.getProviderCode());
            localMerchantRequest.setChannelCode(orderTransferDO.getChannelCode());
            localMerchantRequest.setMchChannelCode(orderTransferDO.getMchChannelCode());
            localMerchantRequest.setSn(orderTransferDO.getSn());
            localMerchantRequest.setAppId(orderTransferDO.getAppId());
            LocalContext.set(localMerchantRequest);
        }
        commonResult.setData(providerChannelConfigDO);
        return commonChannelCallHandler.processTransferLogAndResponse(channelCode, orderTransferDO.getProviderCode(), orderTransferDO.getPayOrderNo(), callBackBody, commonResult);
    }

    String processOrderCallBackErrorResponse(String channelCode, String providerCode, String requestId, String callBackBody, CommonResult commonResult) {
        String serviceName = channelCode + "_order_transfer_callback";
        return commonChannelCallHandler.processTransferLogAndResponse(channelCode, providerCode, requestId, callBackBody, commonResult);
    }

    String processCallBack(String channelCode, NotifyOrderTransferDto notifyOrderTransferDto, ProviderChannelConfigDO providerChannelConfigDO) {
        OrderTransferDO orderTransferDb = transferOrderService.queryPayOrder(notifyOrderTransferDto.getPayOrderNo());
        if (orderTransferDb == null || !StringUtils.hasText(orderTransferDb.getPayOrderNo()) || orderTransferDb.getStatus() == null) {
            return processOrderCallBackErrorResponse(channelCode, providerChannelConfigDO.getProviderCode(), notifyOrderTransferDto.getPayOrderNo(),
                    notifyOrderTransferDto.getCallbackBody(), CommonResult.error(CommonResultCode.PARAMETER_MISSING));
        }
        if (orderTransferDb.getStatus().equals(notifyOrderTransferDto.getStatus().getCode())) {
            log.info("收到转账订单回调,订单实际状态与 回调状态一致 直接返回 payOrderNo:{}", orderTransferDb.getPayOrderNo());
            return processOrderCallBackErrorResponse(channelCode, providerChannelConfigDO.getProviderCode(), orderTransferDb.getPayOrderNo(),
                    notifyOrderTransferDto.getCallbackBody(), CommonResult.success());
        }
        OrderTransferDO updatePayOrderDO = new OrderTransferDO();
        if (notifyOrderTransferDto.getSuccessTime() == null) {
            updatePayOrderDO.setSuccessTime(System.currentTimeMillis());
        }
        else {
            updatePayOrderDO.setSuccessTime(notifyOrderTransferDto.getSuccessTime());
        }
        updatePayOrderDO.setStatus(notifyOrderTransferDto.getStatus().getCode());
        updatePayOrderDO.setMessage(notifyOrderTransferDto.getMessage());
        // 更新数据
        updatePayOrder(updatePayOrderDO, orderTransferDb);
        return processOrderCallBackSuccessResponse(channelCode, orderTransferDb, notifyOrderTransferDto.getCallbackBody(), CommonResult.success(), providerChannelConfigDO);
    }

    void updatePayOrder(OrderTransferDO updatePayOrderDO, OrderTransferDO orderTransferDO) {
        if (MerchantEnum.PROCESS_STATUS.SUCCESS.getCode().equals(updatePayOrderDO.getStatus())) {
            updatePayOrderDO.setNotifyState(CommonEnum.YES_NO_TYPE.YES.getCode());
            if (updatePayOrderDO.getSuccessTime() == null) {
                updatePayOrderDO.setSuccessTime(System.currentTimeMillis());
            }
        }
        updatePayOrderDO.setId(orderTransferDO.getId());
        int count = transferOrderService.updatePayOrderStatus(updatePayOrderDO);
        // 下发状态变更通知
        if (count > 0) {
            if (MerchantEnum.PROCESS_STATUS.SUCCESS.getCode().equals(updatePayOrderDO.getStatus())) {
                // 数据有更新 重新获取一次
                orderTransferDO = transferOrderService.queryPayOrder(orderTransferDO.getPayOrderNo());
                // 订单通知
                orderNotifyHandler.orderNotify(orderTransferDO.getPayOrderNo(), 1, PayOrderEnums.ORDER_STATUS_TYPE.TRANSFER_ORDER_STATUS);
                // 是否自动提现
                if (channelTransferGateway.autoWithdraw(orderTransferDO.getChannelCode())) {
                    OrderWithdrawReq orderWithdrawReq = new OrderWithdrawReq();
                    // orderWithdrawReq.setMchOrderNo(orderTransferDO.getMchOrderNo());
                    orderWithdrawReq.setAmount(MerchantUtils.bigDecimalToString2(orderTransferDO.getAmount()));
                    orderWithdrawReq.setMchChannelCode(orderTransferDO.getInMchChannelCode());
                    // orderWithdrawReq.setClientIp(orderTransferDO.getClientIp());
                    orderWithdrawReq.setRemark("自动提现");
                    CommonResult<OrderWithdrawResp> commonResult = withdrawOrderAppService.submitOrder(orderWithdrawReq);
                    if (!commonResult.isSuccess()) {
                        log.error("转账订单 自动提现失败 payOrderNo:{},message:{}", orderTransferDO.getPayOrderNo(), commonResult.getMsg());
                    }
                }
            }
        }
        else {
            log.info("转账订单 更新订单状态,数据库返回更新的状态与原数据状态一致 直接返回 payOrderNo:{}", orderTransferDO.getPayOrderNo());
        }
    }

    void addPayOrder(OrderTransferDO orderTransferDO) {
        if (MerchantEnum.PROCESS_STATUS.SUCCESS.getCode().equals(orderTransferDO.getStatus())) {
            orderTransferDO.setNotifyState(CommonEnum.YES_NO_TYPE.YES.getCode());
        }
        int count = transferOrderService.updatePayOrderStatus(orderTransferDO);
        // 下发状态变更通知
        if (count > 0) {
            if (MerchantEnum.PROCESS_STATUS.SUCCESS.getCode().equals(orderTransferDO.getStatus())) {
                // 订单通知
                orderNotifyHandler.orderNotify(orderTransferDO.getPayOrderNo(), 1, PayOrderEnums.ORDER_STATUS_TYPE.TRANSFER_ORDER_STATUS);
                // 是否自动提现
                if (channelTransferGateway.autoWithdraw(orderTransferDO.getChannelCode())) {
                    OpenApiOrderWithdrawReq orderWithdrawReq = new OpenApiOrderWithdrawReq();
                    orderWithdrawReq.setMchOrderNo(orderTransferDO.getMchOrderNo());
                    orderWithdrawReq.setAmount(MerchantUtils.bigDecimalToString2(orderTransferDO.getAmount()));
                    orderWithdrawReq.setMchChannelCode(orderTransferDO.getInMchChannelCode());
                    orderWithdrawReq.setClientIp(orderTransferDO.getClientIp());
                    orderWithdrawReq.setRemark("自动提现");
                    CommonResult<OpenApiOrderWithdrawResp> commonResult = withdrawOrderAppService.submitOrder(orderWithdrawReq);
                    if (!commonResult.isSuccess()) {
                        log.error("转账订单 自动提现失败 payOrderNo:{},message:{}", orderTransferDO.getPayOrderNo(), commonResult.getMsg());
                    }
                }
            }
        }
        else {
            log.info("转账订单 更新订单状态,数据库返回更新的状态与原数据状态一致 直接返回 payOrderNo:{}", orderTransferDO.getPayOrderNo());
        }
    }

    /**
     * 支付状态查询
     *
     * @param payOrderDO
     * @return
     */
    @Override
    public boolean queryPayStatus(OrderTransferDO payOrderDO) {
        log.info("转账订单 查询支付中状态 mchOrderNo:{},state:{}", payOrderDO.getMchOrderNo(), payOrderDO.getStatus());
        MerchantEnum.PROCESS_STATUS payOrderStatus = MerchantEnum.PROCESS_STATUS.from(payOrderDO.getStatus());
        switch (payOrderStatus) {
            case INIT:
            case DOING:
                boolean extensionExist = channelTransferGateway.extensionExist(payOrderDO.getChannelCode());
                if (extensionExist) {
                    OrderTransferDO updartePayOrderDO = channelTransferGateway.queryChannelOrder(payOrderDO);
                    if (updartePayOrderDO != null && updartePayOrderDO.getStatus() != null) {
                        // 二者数据不一致 需要更新数据
                        if (!updartePayOrderDO.getStatus().equals(payOrderDO.getStatus())) {
                            // 更新后的熟悉进行复制
                            payOrderDO.setChannelOrderNo(updartePayOrderDO.getChannelOrderNo());
                            payOrderDO.setSuccessTime(updartePayOrderDO.getSuccessTime());
                            payOrderDO.setStatus(updartePayOrderDO.getStatus());
                            updatePayOrder(updartePayOrderDO, payOrderDO);
                            return false;
                        }
                    }
                    else {
                        return true;
                    }
                    break;
                }
                else {
                    log.info("转账订单 当前通道不支持渠道订单功能 channelCode:{}", payOrderDO.getChannelCode());
                    return false;
                }

        }
        return false;
    }
}
